class Book(val title: String, val author: String, val isbn: String) {
  private var isBorrowed: Boolean = false

  def borrow(): Unit = {
    if (isBorrowed) throw new IllegalStateException("Book is already borrowed")
    isBorrowed = true
  }

  def returnBook(): Unit = {
    if (!isBorrowed) throw new IllegalStateException("Book is not borrowed")
    isBorrowed = false
  }

  def isAvailable: Boolean = !isBorrowed
}

object Book {
  def apply(title: String, author: String, isbn: String): Book =
    new Book(title, author, isbn)
  def unapply(book: Book): Option[(String, String, String)] = Some(
    (book.title, book.author, book.isbn)
  )
}

class Library {
  private var availableBooks: List[Book] = Nil
  private var borrowedBooks: List[Book] = Nil

  def addBook(book: Book): Unit = availableBooks = book :: availableBooks

  def borrowBook(isbn: String): Unit = {
    availableBooks.find(_.isbn == isbn) match {
      case Some(book) =>
        book.borrow()
        availableBooks = availableBooks.filterNot(_ == book)
        borrowedBooks = book :: borrowedBooks
      case None => throw new Exception(s"Book $isbn not available")
    }
  }

  def returnBook(isbn: String): Unit = {
    borrowedBooks.find(_.isbn == isbn) match {
      case Some(book) =>
        book.returnBook()
        borrowedBooks = borrowedBooks.filterNot(_ == book)
        availableBooks = book :: availableBooks
      case None => throw new Exception(s"Book $isbn not borrowed")
    }
  }
}
